
package com.probiz.estore.core.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

import com.probiz.estore.core.util.ContextUtil;

public class DownloadView extends AbstractUrlBasedView {
	private static final Log	log	= LogFactory.getLog(DownloadView.class);
	/**
	 * 要下载的文件全路径
	 */
	private String				path;
	/**
	 * 文件题目，如果有必须带后缀格式
	 */
	private String				title;

	private DownloadView() {

	}

	public DownloadView(String path) {
		super();
		this.path = path;
	}

	public DownloadView(String path, String title) {
		super();
		this.path = path;
		this.title = title;
	}

	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		File r;
		FileInputStream in = null;
		try {
			r = new File(path);
			in = new FileInputStream(r);
			if (!r.isFile()) {
				return;
			}
		} catch (SecurityException se) {
			throw (new ServletException("Servlet lacks appropriate privileges."));
		}

		String mimeType = ContextUtil.getServletContext().getMimeType(path);
		if (mimeType == null) {
			mimeType = "text/plain";
		}

		String fileName = "";
		if (StringUtils.isNotBlank(title)) {
			fileName = title;
		} else if(path.contains("\\")){
			fileName = path.substring(path.lastIndexOf("\\") + 1);
		}else if(path.contains("/")){
			fileName = path.substring(path.lastIndexOf("/") + 1);
		}else{
			fileName = "download";
		}
		// 解决中文文件名乱码问题 参考:http://soft.chinabyte.com/database/7/11477007.shtml
		if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
		} else {
			fileName = fileName.replaceAll("\\s+", "+"); // 将空格换成+号
			fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 如果是其他浏览器
		}
		response.setHeader("Content-Disposition", "attachment; filename="
				+ fileName);
		response.setContentType(mimeType);

		OutputStream out = response.getOutputStream();
		byte[] buf = new byte[1024];
		int count = 0;

		while ((count = in.read(buf)) >= 0) {
			out.write(buf, 0, count);
		}
		out.close();
		in.close();
	}
}
